import { ValueStore } from "maishu-chitu";
import React = require("react");
import { subscribe } from "common";
import { PageContext, Application, Page } from "maishu-chitu-react";
import { ComponentProps } from "maishu-jueying";
import { ShoppingCartService } from "mobile/services/shoppingCartService";
import { ShoppingService } from "mobile/services/shoppingService";
import { MemberService } from "mobile/services/memberService";
import { createService, BaseComponent } from "components/common/base-component";
import * as ui from "maishu-ui-toolkit";
import { imageUrl } from "services/service";
import { component } from "components/common/component";

export type ComponentStatus = 'normal' | 'edit'
// export let status = new ValueStore<ControlStatus>('normal');
// export let deleteItemsCount = new ValueStore<number>(0);


export interface ShoppingCartState {
    items?: ShoppingCartItem[], status?: ComponentStatus,
    totalAmount?: number, selectedCount?: number,
    editSelectedItems: Array<ShoppingCartItem>,
    // inputCounts: { [key: string]: number }

}

export interface ShoppingCartlProps extends ComponentProps<ShoppingCart> {
    hideMenu: boolean, pageName: string,
}




@component()
export class ShoppingCart extends BaseComponent<
ShoppingCartlProps,
ShoppingCartState>{

    private shoppingCart: ShoppingCartService;
    private shop: ShoppingService;
    private member: MemberService;

    constructor(props) {
        super(props);

        this.shoppingCart = createService(ShoppingCartService);
        this.shop = createService(ShoppingService);
        this.member = createService(MemberService);

        this.state = {
            status: 'normal',
            items: ShoppingCartService.items.value,
            editSelectedItems: [],
        };
    }

    private async checkItem(item: ShoppingCartItem) {
        if (this.state.status == 'edit') {
            let { editSelectedItems } = this.state;

            if (editSelectedItems.indexOf(item) >= 0) {
                editSelectedItems = editSelectedItems.filter(o => o != item);
            }
            else {
                editSelectedItems.push(item);
            }

            this.setState({ editSelectedItems });
            return;
        }

        if (item.Selected == false)
            await this.shoppingCart.selectItem(item.Id);
        else
            await this.shoppingCart.unselectItem(item.Id);

    }

    async removeSelectedItems() {
        let items: ShoppingCartItem[] = this.state.editSelectedItems;
        await this.shoppingCart.removeItems(items.map(o => o.Id));
        this.setDeleteItems([]);
    }

    private decreaseCount(item: ShoppingCartItem) {
        let itemCount = item.Count;//this.state.inputCounts[item.Id] || 
        if (itemCount <= 1) {
            ui.confirm({
                message: `确定要删除'${item.Name}'吗？`,
                confirm: async () => {
                    await this.shoppingCart.removeItems([item.Id]);
                    let deleteItems = this.state.editSelectedItems.filter(o => o.Id != item.Id);
                    this.setDeleteItems(deleteItems);
                }
            })
            return;
        }
        this.changeItemCount(item, `${(itemCount) - 1}`);
    }
    private increaseCount(item: ShoppingCartItem) {
        let itemCount = item.Count + 1;
        this.changeItemCount(item, `${itemCount}`);
    }
    private changeItemCount(item: ShoppingCartItem, value: string) {
        let count = Number.parseInt(value);
        if (!count) return;

        item.Count = count;
        this.setState(this.state);
    }

    // cancel() {
    //     status.value = "normal";
    //     this.setState({ status: status.value });
    // }

    // edit() {
    //     if (this.state.status == 'normal') {
    //         // this.state.status = 'edit';
    //         // status.value = this.state.status;
    //         // this.setState(this.state);
    //         status.value = "edit";
    //         this.setState({ status: "edit" });

    //         return Promise.resolve();
    //     }

    //     let inputCounts = this.state.inputCounts;
    //     let itemIds = new Array<string>();
    //     let quantities = new Array<number>();
    //     for (let i = 0; i < this.state.items.length; i++) {
    //         let item = this.state.items[i];
    //         if (inputCounts[item.Id] != null && inputCounts[item.Id] != item.Count) {
    //             itemIds.push(item.Id);
    //             quantities.push(inputCounts[item.Id]);
    //         }
    //     }


    //     let result: Promise<any>;
    //     if (itemIds.length > 0) {
    //         result = this.shoppingCart.setItemsCount(itemIds, quantities);
    //     }
    //     else {
    //         result = Promise.resolve({});
    //     }

    //     result.then(() => {
    //         // this.state.status = 'normal';
    //         // status.value = this.state.status;
    //         // this.setState(this.state);
    //         status.value = "normal";
    //         this.setState({ status: status.value });
    //     });

    //     return result;
    // }
    checkAll() {
        if (this.state.status == 'normal') {
            return this.shoppingCart.selectAll();
        }

        this.setDeleteItems(this.state.items);
    }

    uncheckAll() {
        if (this.state.status == 'normal') {
            return this.shoppingCart.unselectAll();
        }

        this.setDeleteItems([]);
    }

    private setDeleteItems(items: ShoppingCartItem[]) {
        this.setState({ editSelectedItems: items });

        // deleteItemsCount.value = items.length;
    }

    async buy() {
        if (this.state.selectedCount <= 0)
            return;

        var items = this.state.items.filter(o => o.Selected);
        var productIds = items.map(o => o.ProductId);
        var quantities = items.map(o => o.Count);
        let userInfo = await this.member.userInfo();
        let memberName = userInfo.Mobile || '';
        let order = await this.shop.createOrder(memberName, productIds, quantities);
        this.app.redirect("shopping/orderProducts", { id: order.Id });

        return order;
    }

    private isChecked(item: ShoppingCartItem) {
        if (this.state.status == 'normal') {
            return item.Selected;
        }
        return this.state.editSelectedItems.indexOf(item) >= 0;
    }


    removeConfirmText() {
        let items: ShoppingCartItem[] = this.state.editSelectedItems;
        let str = "是否要删除？<br/> " + items.map(o => '<br/>' + o.Name);
        return str;
    }

    componentDidMount() {
        subscribe(this, ShoppingCartService.items, (value) => {
            this.setState({ items: value })
        })
    }

    render() {

        if (this.state.editSelectedItems == null || this.state.items == null)
            return <></>

        let items = this.state.items;
        console.assert(items != null);

        return items.length > 0 ?
            <div className="shopping-shoppingCart container">
                <ul className="list-group">
                    {items.map(o =>
                        <li key={o.Id} className="list-group-item row">
                            {o.Type == null ?
                                <button onClick={() => this.checkItem(o)} className="pull-left icon">
                                    <i className={this.isChecked(o) ? 'icon-ok-sign' : 'icon-circle-blank'}></i>
                                </button> : null}
                            <div className="pull-left pic"
                                onClick={() => this.app.forward("home/product", { id: o.ProductId })}>
                                {o.Type == 'Reduce' || o.Type == 'Discount' ?
                                    <div className={o.Type}>
                                        {o.Type == 'Reduce' ? '减' : '折'}
                                    </div>
                                    :
                                    <img src={imageUrl(o.ImagePath)} style={{ width: "100%", height: "100%" }}
                                        ref={(e: any) => e ? ui.renderImage(e) : null} />}
                            </div>
                            <div style={{ marginLeft: 100 }}>
                                <div onClick={() => this.checkItem(o)} >{o.Name}</div>
                                <div style={{ height: 42, paddingTop: 4 }}>
                                    <div className="price pull-left" style={{ marginTop: 10 }}>{o.Price ? "￥" + o.Price.toFixed(2) : ""}</div>
                                    <div className="pull-right" style={{ marginTop: 4 }}>
                                        {this.state.status == 'normal' || o.Type != null ?
                                            <div style={{ paddingLeft: 6 }}>X {o.Count}</div>
                                            :
                                            <div className="input-group" style={{ width: 120, display: 'table' }}>
                                                <span onClick={() => this.decreaseCount(o)} className="input-group-addon">
                                                    <i className="icon-minus"></i>
                                                </span>
                                                <input value={`${o.Count}`} className="form-control" type="text" style={{ textAlign: 'center' }}
                                                    onChange={(e) => (this.changeItemCount(o, (e.target as HTMLInputElement).value))} />
                                                <span onClick={() => this.increaseCount(o)} className="input-group-addon">
                                                    <i className="icon-plus"></i>
                                                </span>
                                            </div>
                                        }
                                    </div>
                                </div>
                            </div>
                        </li>
                    )}
                </ul>
            </div>
            :
            <div className="norecords">
                <div className="icon">
                    <i className="icon-shopping-cart">

                    </i>
                </div>
                <h4 className="text">你的购买车空空如也</h4>
            </div>
    }
}